﻿ /* 
 * 作者 :   qiaojianhui
 * 创建时间:2010/6/14 17:11:45
 * Email:   qiaojianhui@cont.com.cn
 * 用途:    
 * 历史:    2010/6/14 17:11:45 由 qiaojianhui 创建
 */

using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;

namespace oqis.core.common.winsys
{
    /// <summary>
    /// ConsoleIO
    /// </summary>
    public class ConsoleIO
    {
        /// <summary>
        /// 类构建
        /// </summary>
        public ConsoleIO() { ConsoleWindow.CreateConsole(); }

        /// <summary>
        /// 输出控制台信息
        /// </summary>
        /// <param name="info"></param>
        public void Output(string info) { Console.WriteLine(info); }

        /// <summary>
        /// 获取控制台输入信息
        /// </summary>
        /// <returns></returns>
        public string Input() { return Console.ReadLine(); }
    }

    /// <summary>
    /// 自定义的控制台窗口
    /// </summary>
    public class ConsoleWindow
    {
        /// <summary>
        /// 创建自定义的控制台窗口
        /// </summary>
        /// <returns></returns>
        public static IntPtr CreateConsole()
        {
            var console = new ConsoleWindow();
           
            return console.Hwnd;
        }

        /// <summary>
        /// 窗体句柄
        /// </summary>
        public IntPtr Hwnd { get; private set; }

        /// <summary>
        /// 控制台窗体
        /// </summary>
        public ConsoleWindow()
        {
            Initialize();
        }

        /// <summary>
        /// 初始化
        /// </summary>
        public void Initialize()
        {
            Hwnd = GetConsoleWindow();

            // Console app
            if (Hwnd != IntPtr.Zero)
            {
                return;
            }

            // Windows app
            AllocConsole();
            Hwnd = GetConsoleWindow();
        }

        #region Win32 dll

        [DllImport("kernel32")]
        static extern IntPtr GetConsoleWindow();

        [DllImport("kernel32")]
        static extern bool AllocConsole();


        #endregion
    }
}
